<template>  
  <div class="inspection-upload">  
    <!-- 顶部导航栏 -->  
    <van-nav-bar  
      title="巡检记录上传"  
      left-text="返回"  
      left-arrow  
      @click-left="onBack"  
      right-text="关闭"  
      @click-right="onClose"  
    />  
    <el-form :model="form" label-position="top" label-width="100px">   
    <!-- 内容区域 -->  
    <div class="content">  
      <van-cell-group>
         
        <!-- 保养位置 -->  
        <van-cell title="保养位置">  
          
            <el-form-item label="">  
            <!-- 如果已经获取到经纬度，则显示，否则显示占位文字 -->  
            <span v-if="locationReady" class="grey-text">  
                经度：{{ location.longitude }}，纬度：{{ location.latitude }}  
            </span>  
            <span v-else class="grey-text">  
                正在获取当前位置...  
            </span>  
            </el-form-item>  

            <!-- 手动重新获取按钮 -->  
            <el-button type="primary" plain size="mini" @click="getLocation">重新获取位置</el-button>  
         
        </van-cell>  

        <!-- 开始时间 -->  
        <van-cell title="开始时间">  
             <!-- 开始时间 -->  
            <el-form-item label="" required>  
            <el-date-picker  
                v-model="form.startTime"  
                type="datetime"  
                placeholder="请选择开始时间"   
                @change="onTimeChange"  
                format="yyyy-MM-dd HH:mm:ss"  
            ></el-date-picker>  
            </el-form-item>  
              
        </van-cell>  

        <!-- 巡检人 -->  
        <van-cell title="巡检人">  
            <el-form-item label="" required v-model="form.userName" >  
                <span class="grey-text" key="">{{user.userName}}</span>  
            </el-form-item>  
        </van-cell>  

        <!-- 已完成/未完成状态 -->  
        <van-cell title="完成情况">  
          <van-radio-group v-model="form.completionStatus" direction="horizontal">  
            <van-radio name="complete">已完成</van-radio>  
            <van-radio name="incomplete">未完成</van-radio>  
          </van-radio-group>  
        </van-cell>  
      </van-cell-group>  

      <!-- 现场情况 -->  
      <div class="section">  
        <div class="section-title">  
          现场情况 <span class="note">( 照片自动加水印 )</span>  
        </div>  
        <van-field  
          v-model="form.situation"  
          placeholder="请输入现场情况"  
          rows="3"  
          type="textarea"  
          autosize  
          maxlength="180"  
          show-word-limit  
        >  
        
      
        </van-field>  
          <van-uploader v-model="reportPhotos" :max-count="1" /> 
      </div>  

      <!-- 抄送对象 -->  
      <div class="section">  
        <div class="section-title">抄送对象</div>  
        <el-button type="primary" plain @click="openCCTargetDialog">选择抄送对象</el-button>  
        <div class="selected-cc">  
          <span  
            v-for="(person, index) in selectedCC"  
            :key="index"  
            class="selected-person"  
          >  
            {{ person }}  
            <i  
              class="el-icon-close"  
              @click="removePerson(index)"  
            ></i>  
          </span>  
        </div>  
      </div>  

      <!-- 提交按钮 -->  
      <div class="submit-button">  
        <van-button type="primary" block @click="onSubmit">立即提交</van-button>  
      </div> 
    
    </div>  
    </el-form> 

    <!-- 抄送对象对话框 -->  
    <el-dialog title="选择抄送对象" :visible.sync="ccDialogVisible">  
      <el-form>  
        <el-form-item label="请选择人员">  
          <el-select v-model="form.selectedPerson" placeholder="请选择">  
            <el-option  
              v-for="person in ccOptions"  
              :key="person"  
              :label="person"  
              :value="person"  
            ></el-option>  
          </el-select>  
        </el-form-item>  
      </el-form>  
      <div slot="footer" class="dialog-footer">  
        <el-button @click="ccDialogVisible = false">取消</el-button>  
        <el-button type="primary" @click="confirmCCPerson">确定</el-button>  
      </div>  
    </el-dialog>  
  </div>  
</template>  

<script>  
import {getUser,inspectionRecordUpload} from "@/api/wushui/inspection";
export default {  
  data() {  
    return {  
         // 抄送对象功能相关  
      ccDialogVisible: false, // 对话框是否显示  
      ccOptions: ["张三", "李四", "王五", "赵六"], // 人员选项  
      selectedCC: [], // 已选择的抄送对象 

      form: { 
        planId : '',
        selectedPerson:null,
        userName:'',
        startTime: null, // 开始时间  
        completionStatus: "complete", // 完成情况 (已完成/未完成)  
        situation: "", // 输入的现场情况  
      },
      location: {  
        latitude: null, // 纬度  
        longitude: null, // 经度  
      },  
      locationReady: false, // 表示是否获取到位置信息  
     
      reportPhotos: [], // 上传的汇报对象图片  
      ccPhotos: [], // 上传的抄送对象图片  
      user:{}
    };  
  },  

  created(){
    this.getUser();
  },
  mounted() {  
    const { planId } = this.$route.query;  
    this.form.planId = planId;
  }  ,
  methods: {  
    // 打开对话框  
    openCCTargetDialog() {  
      this.ccDialogVisible = true;  
    },  

    // 确认选择人员  
    confirmCCPerson() {  
      if (this.form.selectedPerson && !this.selectedCC.includes(this.form.selectedPerson)) {  
        this.selectedCC.push(this.form.selectedPerson); // 不重复添加选择  
      }  
      this.form.selectedPerson = null; // 重置当前选择  
      this.ccDialogVisible = false; // 关闭对话框  
    },  

    // 移除选中的人员  
    removePerson(index) {  
      this.selectedCC.splice(index, 1); // 从数组中删除  
    },  
    getUser(){
        getUser().then((response) => {
          this.user = response;
          this.form.userName = this.user.userName
        }).catch(() => {
          this.$message.error("获取数据失败");
        });  
    },
    onTimeChange(value) {  
      console.log('选择的时间为:', value);  
    },  
    
    // 获取设备位置  
    getLocation() {  
      if (navigator.geolocation) {  
        this.locationReady = false; // 重置状态  
        navigator.geolocation.getCurrentPosition(  
          (position) => {  
            // 成功获取位置  
            const { latitude, longitude } = position.coords;  
            this.location = { latitude, longitude };  
            this.locationReady = true;  
          },  
          (error) => {  
            // 获取失败  
            let message = '';  
            switch (error.code) {  
              case 1:  
                message = '用户拒绝访问位置信息';  
                break;  
              case 2:  
                message = '位置信息不可用';  
                break;  
              case 3:  
                message = '获取位置信息超时';  
                break;  
              default:  
                message = '未知错误';  
            }  
            this.$message.error(`定位失败：${message}`);  
          },  
          {  
            enableHighAccuracy: true, // 提高精确度  
            timeout: 10000, // 超时时间  
            maximumAge: 60000, // 缓存时间  
          }  
        );  
      } else {  
        this.$message.error('当前设备或浏览器不支持地理定位！');  
      }  
    },  
    onBack() {  
      this.$router.go(-1);  
    },  
    onClose() {  
      this.$router.push("/home");  
    }, 
    onUploadPhoto() {  
      alert("上传照片功能");  
    },  
    onSubmit() {  
      event.preventDefault();
       inspectionRecordUpload(this.form).then((response) => {
          console.log(response)
          if(response.code == 200 ){
             this.$message({ message: '上传成功!', type: 'success',  duration: 1000, // 提示持续时间（毫秒）  
                onClose: () => {  
                    this.$router.push({ path: '/inspection' }); // 在提示关闭后跳转  
                }  
            });  
             
          }
        }).catch(() => {
          this.$message.error("获取数据失败");
        });  
      
    },  
  },  
};  
</script>  

<style scoped>  
.section {  
  margin-bottom: 20px;  
}  

.section-title {  
  font-size: 16px;  
  font-weight: bold;  
  margin-bottom: 10px;  
}  

.selected-person {  
  display: inline-block;  
  margin-right: 5px;  
  padding: 2px 8px;  
  background-color: #f0f0f0;  
  border: 1px solid #dcdcdc;  
  border-radius: 4px;  
  position: relative;  
}  

.selected-person .el-icon-close {  
  margin-left: 5px;  
  cursor: pointer;  
}  

.dialog-footer {  
  text-align: right;  
}  

/* 父容器样式 */  
.inspection-upload {  
  background-color: #f4f4f4;  
  min-height: 100vh;  
}  

/* 顶部导航栏 */  
.van-nav-bar {  
  position: sticky;  
  top: 0;  
  z-index: 10;  
  background-color: #ffffff;  
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.2);  
}  

/* 内容区域 */  
.content {  
  padding: 16px;  
}  

/* 文字样式 */  
.grey-text {  
  color: #888;  
}  

/* 小节区域背景 */  
.section {  
  margin: 16px 0;  
  padding: 12px;  
  background: #ffffff;  
  border-radius: 8px;  
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);  
}  

/* 小节标题 */  
.section-title {  
  font-size: 16px;  
  font-weight: bold;  
  margin-bottom: 10px;  
}  

/* note 样式 */  
.note {  
  font-size: 12px;  
  color: #999;  
}  

/* 上传照片图标 */  
.photo-icon {  
  font-size: 20px;  
  margin-right: 10px;  
  color: #666;  
}  

/* 提交按钮 */  
.submit-button {  
  margin-top: 24px;  
}  
</style>